package com.tianji.learning.mq;

import cn.hutool.core.util.ObjectUtil;
import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.learning.service.ILearningLessonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class LessonChangeListener {

    //注入课表的service
    @Autowired
    ILearningLessonService learningLessonService;


    /**
     * 支付或报名课程后，立刻加入课表
     * @param orderBasicDTO
     */
    //创建并监听指定key的交换机队列
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConstants.Queue.LEARNING_LESSON_PAY_QUEUE, durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE,type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_PAY_KEY
    ))
    public void listenLessonPay(OrderBasicDTO orderBasicDTO) {
        //判空，如果用户id或者课程id有一个为空则结束
        if (ObjectUtil.isEmpty(orderBasicDTO) || ObjectUtil.isEmpty(orderBasicDTO.getUserId()) || ObjectUtil.isEmpty(orderBasicDTO.getCourseIds())){
            log.info("订单支付异常消息："+ orderBasicDTO);
            return;
        }

        //记录mq监听到的消息
        log.info("监听到用户：{}的订单{}的支付消息，需要添加课程：{}至用户的课表，",orderBasicDTO.getUserId(),orderBasicDTO.getOrderId(),orderBasicDTO.getCourseIds());
        //通过课程表的service添加课程，两个参数：一个是用户id，一个是课程id
        learningLessonService.addLearningLesson(orderBasicDTO.getCourseIds(),orderBasicDTO.getUserId());

    }


    /**
     * 退款后，立刻移除课表中的课程
     * @param order
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConstants.Queue.LEARNING_LESSON_REFUND_QUEUE, durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE,type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_REFUND_KEY
    ))
    public void listenLessonTrade(OrderBasicDTO order){
        // 1.健壮性处理
        if(order == null || order.getUserId() == null || CollUtils.isEmpty(order.getCourseIds())){
            // 数据有误，无需处理
            log.error("接收到MQ消息有误，订单数据为空");
            return;
        }
        // 2.添加课程
        log.debug("监听到用户{}的订单{}要退款，需要删除课程{}", order.getUserId(), order.getOrderId(), order.getCourseIds());
        learningLessonService.deleteCourseFromLesson(order.getUserId(), order.getCourseIds().get(0));
    }

}
